package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatPayUtil;
    @Autowired
    private UserMapper userMapper;

    /**
     * 微信登录
     * @param dto
     * @return
     */
    @Override
    public User login(UserLoginDTO dto) {
        //1.通过httpclient 调用微信接口服务，获取微信用户信息（构造登录凭证校验请求）
        //构造请求参数
        Map<String ,String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatPayUtil.getAppid());
        paramMap.put("secret",weChatPayUtil.getSecret());
        paramMap.put("js_code",dto.getCode());
        paramMap.put("grant_type","authorization_code");
        //调用HttpClientUtil工具类，发送请求，获取响应结果
        String res = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        log.info("微信登录返回结果：{}",res);

        //2.解析响应结果，获取openid
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = (String) jsonObject.get("openid");
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //根据openid查询数据库user表，判断该用户是否已经完成注册
        User user = userMapper.selectByOpenid(openid);
        //如果是新用户，初始化用户数据，保存到数据库user表中
        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        //如果是老用户，返回user对象数据
        return user;
    }
}
